<template>
  <div class="login-content" v-if="visible">
    <div class="header">
      <span @click="closeDialog" class="show">×</span>
      <div class="log" @click="toggleForm(true)" :class="{ active: isLogin }">登录</div>
      <div class="reg" @click="toggleForm(false)" :class="{ active: !isLogin }">注册</div>
    </div>

    <el-form :model="form" :rules="rules" ref="formRef" class="form">
      <el-select v-model="selectRole" placeholder="选择身份" class="select">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-form-item prop="userName">
        <el-input :prefix-icon="User" v-model="form.userName"></el-input>
      </el-form-item>

      <el-form-item prop="userPassword">
        <el-input
          type="password"
          :prefix-icon="Lock"
          v-model="form.userPassword"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item>
        <el-button
          :loading="loading"
          class="login_btn"
          type="primary"
          size="default"
          @click="handleSubmit"
          >{{ isLogin ? '登录' : '注册' }}</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import useUserStore from '@/stores/modules/user'

const isLogin = ref(true)
const form = reactive({ userName: '15231280032', userPassword: '12345678' })
const loading = ref(false)
const $router = useRouter()
const $route = useRoute()
const useStore = useUserStore()
const formRef = ref()

const selectRole = ref('')
const value1 = ref('')

const options = [
  {
    value: 'customer',
    label: '用户',
  },
  {
    value: 'borrower',
    label: '借卖方',
  },
  {
    value: 'brand',
    label: '品牌方',
  },
  {
    value: 'admin',
    label: '管理员',
  },
]
const props = defineProps({
  visible: Boolean,
})

const emit = defineEmits(['update:visible'])

const toggleForm = (login: boolean) => {
  isLogin.value = login
  form.userName = ''
  form.userPassword = ''
  selectRole.value = ''
}

const validatorUserName = (rule: any, value: any, callback: any) => {
  if (value.length === 11) callback()
  else callback(new Error('请输入11位用户名'))
}

const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.length >= 8 && value.length <= 16) callback()
  else callback(new Error('请输入8-16位密码'))
}
const rules = {
  userName: [{ trigger: 'change', validator: validatorUserName }],
  userPassword: [{ trigger: 'change', validator: validatorPassword }],
}

const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  try {
    if (isLogin.value) {
      console.log(value1.value)
      const { userName, userPassword } = form
      await useStore.userLogin(userName, userPassword, selectRole.value)
      ElNotification({
        type: 'success',
        message: '欢迎回来',
      })
      if (useStore.role !== 'admin') {
        await useStore.userInfo()
        const redirect: any = $route.query.redirect
        $router.push({ path: redirect || '/' })
      } else {
        $router.push({ path: '/admin' })
      }
      useStore.hideLoginModal() // 登录成功后关闭对话框
    } else {
      const { userName, userPassword } = form
      const defaultName = userName.slice(7)
      await useStore.userRegister(userName, defaultName, userPassword, selectRole.value)
      ElNotification({
        type: 'success',
        message: '注册成功，请登录。',
      })
      toggleForm(true)
    }
  } catch (error) {
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  } finally {
    loading.value = false
  }
}
// 关闭对话框时更新状态
const closeDialog = () => {
  emit('update:visible', false)
}
</script>
<style scoped lang="scss">
.login-content {
  width: 300px;
  height: 350px;
  transform: translate(-50%, -50%);
  padding: 30px 50px;
  margin: 0px;
  border: 0;
  border-radius: 10px;
  box-shadow: 0px 0px 5px rgba(28, 27, 27, 0.381);
  background-color: #ffffff;

  .header {
    margin: 0 auto;
    padding: 10px 0 45px 0;
    font-size: 24px;
    color: #000000af;
    cursor: default;
    .show:hover {
      color: #000000;
      font-size: 18px;
    }
    .active {
      color: #000000;
    }
    .show {
      position: absolute;
      right: 15px;
      top: 15px;
      font-size: 16px;
    }
    .log {
      display: inline-block;
      width: 50%;
      border-right: 1px solid rgba(108, 90, 90, 0.521);
      text-align: center;
    }
    .reg {
      display: inline-block;
      width: 50%;
      text-align: center;
    }
  }
  .form {
    .select {
      margin: 0 0 18px 0;
    }
    .login_btn {
      margin: 20px 0 10px 0;
      width: 100%;
    }
  }
}
</style>
